/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    // 先序遍历二叉树后重构链表
    public void flatten1(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<>();
        TreeNode cur = root;
        preOrder(cur, queue);
        root = queue.poll();
        while(!queue.isEmpty()){
            cur = queue.poll();
            root.left = null;
            root.right = cur;
            root = root.right;
        }
    }
    public void preOrder(TreeNode root, Queue<TreeNode> queue){
        if(root == null){
            return ;
        }
        queue.offer(root);
        preOrder(root.left, queue);
        preOrder(root.right, queue);
    }
    // 寻找前驱节点
    public void flatten2(TreeNode root) {
       TreeNode curNode = root;
       while(curNode != null){
            if(curNode.left != null){
                TreeNode next = curNode.left;
                TreeNode preNode = next;
                while(preNode.right != null){
                    preNode = preNode.right;
                }
                preNode.right = curNode.right;
                curNode.right = next;
                curNode.left = null;
            }
            curNode = curNode.right;
       }
    }
}